package com.example.lottery.service;

import com.example.lottery.config.LotteryConfig;
import com.example.lottery.entity.Award;
import com.example.lottery.entity.Winner;
import com.example.lottery.mapper.LotteryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Random;

/**
 * @author 23050
 * @version 1.0
 * @description: TODO
 * @date 2023/12/5 14:31
 */
@Service
public class LotteryService {

    //奖项信息
    @Autowired
    private LotteryConfig lotteryConfig;

    @Autowired
    private LotteryMapper lotteryMapper;




    //抽奖
    public final synchronized Winner lottery(HashMap<Integer,Integer> residueAwards) {


        //这个人开始抽奖，返回结果为Winner对象，名字就是 奖项+第几个抽中的奖
        Award award = getAWard();
        //如果没有抽中
        if (award==null){
            return null;
        }
        //获奖了，将获奖人信息存到数据库中
        //判断这个奖是否还有剩余
        int awardId = award.getId(); //抽的是几等奖
        int awardCount = residueAwards.get(awardId);  //这个奖剩下的数量
        if (awardCount==0){//如果没有剩余这个奖，相当于没有抽中
            return null;
        }

        //更新剩余的奖的数量
        residueAwards.put(award.getId(),awardCount-1);
        Winner winner = new Winner();
        //得奖人编号
        int winnerId = lotteryConfig.getLotteryNumber()-residueAwards.get(1)-residueAwards.get(2)-residueAwards.get(3);
//        System.out.println(residueAwards.get(1));
//        System.out.println(residueAwards.get(2));
//        System.out.println(residueAwards.get(3));
//        System.out.println(lotteryConfig.getLotteryNumber());
        winner.setId(winnerId);
        winner.setName(winnerId + award.getDescribe());
        winner.setAwardId(awardId);

        //将这个winner存到数据库中
        int ret = lotteryMapper.save(winner);


        return winner;
    }

    //抽奖方法
    private Award getAWard() {
        //开始抽奖
        //假设奖项一:1%   奖项二:2%  奖项三:3%    未中奖:94%
        //取1-10的随机数，1为一等奖   2-3为二等奖     4-6为三等奖   7-10未中奖

        Random random = new Random();
        //生成随机数
        int awardNum = random.nextInt(100)+1;
        //判断奖项
        if (awardNum<=1){
            //一等奖
            return lotteryConfig.getAwards().get(0);
        }else if(awardNum<=3){
            //二等奖
            return lotteryConfig.getAwards().get(1);
        }else if(awardNum<=6){
            //三等奖
            return lotteryConfig.getAwards().get(2);
        }else{
            return null;
        }

    }





}




















